package com.example.dell.library.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.dell.library.R;
import com.example.dell.library.activity.BookInforActivity;
import com.example.dell.library.bean.Book;
import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.ViewHolder> {
    private Context context;
    private List<Book> mBookList;

    public class ViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        ImageView bookImage;
        TextView bookName;
        TextView bookIsInIt;
        View bookView;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            bookView = view;
            cardView = (CardView) view;
            bookImage = (ImageView) view.findViewById(R.id.book_img);
            bookName = (TextView) view.findViewById(R.id.book_name);
            bookIsInIt = (TextView) view.findViewById(R.id.book_isInIt);
        }
    }

    public BookAdapter(List<Book> bookList) {
        mBookList = bookList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (context == null) {
            context = parent.getContext();
        }
        View view = LayoutInflater.from(context).inflate(R.layout.book_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        holder.bookView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Book book = mBookList.get(position);
                Intent intent = new Intent(context, BookInforActivity.class);
                intent.putExtra("BOOK", new Gson().toJson(book));
                context.startActivity(intent);
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Book book = mBookList.get(position);
        if (book.getBookNums() > 0 && book.getInIt() == true) {
            Glide.with(context).load(book.getImgFile().getUrl()).into(holder.bookImage);
            holder.bookName.setText(book.getName());
            holder.bookIsInIt.setText("在馆");
        }
    }

    @Override
    public int getItemCount() {
        return mBookList.size();
    }
}
